import {Component, OnInit} from '@angular/core';
import {BladeContainerBase} from '../../../../shared/blade/blade-container-base';
import {BladeData} from '../../../../shared/blade/blade-data';
import {Blade} from '../../../../shared/blade/blade.model';
import {Command} from '../../../../shared/toolbar.service';
import {DialogResult} from '../../../../shared/dialog.service';
import {Observable} from 'rxjs/Observable';

import {Circuit} from '../../../../entity/circuit.model';
import {CircuitEditComponent} from '../circuit-edit/circuit-edit.component';
import {CircuitService} from '../../../../service/circuit.service';


//风场服务，数据模型
import {FarmService} from '../../../../service/farm.service';
import {Farm} from '../../../../entity/farm.model';
//工期服务数据模型
import {PhaseService} from '../../../../service/phase.service';
import {Phase} from '../../../../entity/phase.model';


@Component({
  selector: 'app-circuit-list',
  templateUrl: './circuit-list.component.html',
  styleUrls: ['./circuit-list.component.css']
})

export class CircuitListComponent extends BladeContainerBase<Circuit> {

  public circuits: Circuit[] = [];
  public original: Circuit[] = [];

  private farms: Farm[] = [];     //全部风场
  private allPhases: Phase[] = [];  //全部工期
  private farmPhases: Phase[] = []  //风场下边的工期

  constructor(
    private circuitService: CircuitService,
    private farmService: FarmService,
    private phaseService: PhaseService
  ) {
    super();
  }

  ngOnInit() {
    this.commands = [
      new Command('add', '添加', 'fa fa-plus', 'setofkey:insert', blade => this.exeAdd(blade), blade => this.canExeAdd(blade)),
      new Command('edit', '编辑', 'fa fa-edit', 'setofkey:update', blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
      new Command('delete', '删除', 'fa fa-trash-o', 'setofkey:delete', blade => this.exeDelete(blade), blade => this.canDelete(blade))
    ];
    super.ngOnInit();
  }

  /**
   * 初始化数据
   *
   *
   * @memberof CircuitListComponent
   */
  initData(): any | Observable<any> | Promise<any> {
    let phase = this.phaseService.getPhases();
    let circuit: Promise<Circuit[]>;
    if (this.parentEntity == null) {
      circuit = this.circuitService.getCircuitList();
    }
    else {
      if (this.parentEntity.hasOwnProperty('farmCode')) {
        circuit = this.circuitService.getCircuitByFarmId((this.parentEntity as Farm).farmId);
      }
      else if (this.parentEntity.hasOwnProperty('phaseCode')) {
        circuit = this.circuitService.getCircuitByPhaseId((this.parentEntity as Phase).phaseId);
      }
    }
    if (circuit != null) {
      Promise.all([phase, circuit])
        .then(res => {
          if (res[1]) {
            this.original = [...res[1]];
            this.circuits = [...this.original];
          }
          for (let i = 0; i < this.circuits.length; i++) {
            let phaseIds = this.circuits[i].phaseIds.split(',');
            let phaseNames: string[] = [];
            phaseIds.forEach(phaseId => {
              if (!res[0]) {
                return false;
              }
              ;
              let phaseEntity = res[0].find(o => o.phaseId == Number.parseInt(phaseId));
              if (phaseEntity != null) {
                phaseNames.push(phaseEntity.phaseName);
              } else {
                phaseNames.push(phaseId);
              }
            })
            this.circuits[i].phaseNames = phaseNames.join(',');
          }
        })
        .catch(error => {
          this.bladeData.error = error
        })
        .then(res => this.bladeData.isLoading = false);
    }
  }

  exeAdd(blend: Blade): void {
    let data: BladeData = new BladeData();
    data.id = 'circuitCreate';
    data.title = '新建线路';
    //data.subtitle = "新建线路";
    data.isClosingDisabled = false;
    let createCircuitBlade = this.bladeService.createBlade(CircuitEditComponent, data, true);
    this.bladeService.showBlade(createCircuitBlade, this.currentBlade);
  }

  canExeAdd(blend: Blade): boolean {
    return true;
  }

  exeEdit(blend: Blade): void {
    if (this.currentEntity != undefined) {
      let data: BladeData = new BladeData();
      data.id = 'circuitEdit';
      data.title = this.currentEntity.circuitName;
      let editCircuitBlade = this.bladeService.createBlade(CircuitEditComponent, data, false, this.currentEntity);
      this.currentBlade.bladeService.showBlade(editCircuitBlade, this.currentBlade);
    }
  }

  canExeEdit(blend?: Blade): boolean {
    return this.currentEntity != null;
  }

  exeDelete(blend: Blade): void {
    let selectedCircuits = this.getSelected();
    if (selectedCircuits.length > 0) {
      this.dialogService
        .showConfirmationDialog('确认删除', '是否要删除选中项？')
        .subscribe(dialogResult => {
          if (dialogResult === DialogResult.Ok) {
            this.currentBlade.bladeData.isLoading = true;
            this.circuitService.batchDelete(selectedCircuits.map(o => o.circuitId))
              .then(res => {
                if (res) {
                  this.refresh(undefined);
                }
              })
              .catch(error => this.bladeData.error = error)
              .then(res => this.bladeData.isLoading = false);
          }
        });

    }
  }

  canDelete(blend?: Blade): boolean {
    return this.getSelected().length > 0;
  }

  onSeletedChange(circuit: Circuit) {
    if (this.currentBlade.childrenCanDeactivate()) {
      this.currentEntity = circuit;
    }
  }

  /**
   * 展开线路信息详情列表弹出层
   *
   * @param {Circuit} circuit
   *
   * @memberof CircuitEditComponent
   */
  // showCircuitDetailsBlade(circuit: Circuit) {
  //      if (this.currentEntity != circuit
  //         || this.bladeService.findBlade("circuitDetailsComponent") == undefined) {
  //         let data: BladeData = new BladeData();
  //         data.id = "CircuitDetailsComponent";
  //         data.title = circuit.circuitName + "列表";
  //         data.isClosingDisabled = false;
  //         let circuitListBlade = this.bladeService.createBlade(CircuitEditComponent, data, false, null, circuit);
  //         this.bladeService.showBlade(circuitListBlade, this.currentBlade).then(res => {
  //             if (res) {
  //                 this.currentEntity = circuit;
  //             }
  //         });
  //     }
  // }

  /**
   * 单选
   *
   * @param {any} event
   * @param {any} key
   *
   * @memberof DicKeyListComponent
   */
  onItemCheack(event: HTMLInputElement, key: Circuit) {
    key.isChecked = event.checked;
  }

  /**
   * 全选/全不选
   *
   * @param {HTMLInputElement} event
   *
   * @memberof DicKeyListComponent
   */
  onAllCheack(event: HTMLInputElement) {
    if (this.circuits.length > 0) {
      for (let i = 0; i < this.circuits.length; i++) {
        this.circuits[i].isChecked = event.checked;
      }
    }
  }

  /**
   * 获得选中项
   *
   * @returns {Setofkey[]}
   *
   * @memberof CircuitListComponent
   */
  getSelected(): Circuit[] {
    if (this.circuits.length > 0) {
      let filter = this.circuits.filter(ref => ref.isChecked)
      return filter == null ? [] : filter;
    }
    return [];
  }
}


// WEBPACK FOOTER //
// ./src/app/module/basic/circuit/circuit-list/circuit-list.component.ts
